#!/usr/bin/env bash
export OPER=$1
export FILE=$2
echo "tinycomputer备份脚本v1.0"
function backup(){
if [[ "$OPER" == "backup" ]];then
    if [[ "$FILE" == "" ]];then
    export FILE=/storage/emulated/0/tinycomputer-backup-$(date "+%Y-%m-%d-%H-%M-%S").tar.gz
    echo "开始备份,默认在$FILE"
    for (( i=3;i>0;i-- ));do
    	echo "$i秒后开始备份"
	sleep 1
    done
    tar -cvf - -C /data/data/com.fct.tiny/files/containers ./0|gzip > $FILE 
    else
    tar -cvf - -C /data/data/com.fct.tiny/files/containers ./0|gzip > $FILE
    fi
    echo "备份完成,部分文件备份失败属正常现象。"
elif [[ "$OPER" == "restore" ]];then
    if [[ "$FILE" == "" ]];then
    echo "请先指定一个文件路径."
    return 1
    else
    read -p "即将开始还原数据，现有数据将被清空(不会清空外置存储内容)，请确认是否继续?[y/N]" SEL
    if [[ "$SEL" == "y" || "$SEL" == "Y" ]];then
    for (( i=3;i>0;i-- ));do
        echo "$i秒后开始还原"
	sleep 1
    done
    tar -zxvf $FILE -C /data/data/com.fct.tiny/files/containers --recursive-unlink --preserve-permissions
    echo "还原完成，建议重新启动小小电脑APP以使数据生效。"
    else
	echo "已取消操作"
    fi
    fi
else
    echo "使用方法:$0 <命令> [选项]"
    echo "backup [文件路径]     备份小小电脑容器"
    echo "restore <文件路径>    还原小小电脑容器"
fi
}
if [[ "$SSH_CLIENT" = "" ]];then
	backup $@;
else
	echo "检测到正在使用ssh连接，操作过程中请全程不要断开连接！"
	sleep 1;backup $@
fi
